package com.jlastu.znb.view;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.jlastu.znb.R;
import com.jlastu.znb.entity.Goods;
import com.jlastu.znb.entity.Photo;
import com.jlastu.znb.presenter.DetailPresenter;
import com.jlastu.znb.contract.DetailContract;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DetailsActivity extends AppCompatActivity implements DetailContract.IProductDetailView, View.OnClickListener {

    private LinearLayout xqConfirmLayout;
    private ImageView mBack;
    private TextView quantityTextView;
    private TextView totalPriceTextView;
    private Button plusButton;
    private Button minusButton;
    private int quantity = 1;
    private final double pricePerUnit = 29.9;
    private ImageButton cancelImageButton;
    private ImageView ivCollection,imgProduct,imgProductDetailContainer,mShoppingCart;
    private TextView tvCollectionText,tvProductName,tvProductPrice,tvProductAddress;
    private boolean isCollected = false;
    private Goods goods;
    private DetailContract.IProductDetailPresenter mProductDetailPresenter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        mProductDetailPresenter = new DetailPresenter(this, this);
        tvProductName = findViewById(R.id.xq_goods_name);
        tvProductPrice = findViewById(R.id.xq_price);
        tvProductAddress = findViewById(R.id.xq_address);
        imgProduct = findViewById(R.id.xq_photo1);
        imgProductDetailContainer = findViewById(R.id.xq_photo2);
        mShoppingCart = findViewById(R.id.shoppingcart);
        mBack = findViewById(R.id.back);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }

        });

        mShoppingCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DetailsActivity.this,ShoppingCartActivity.class);
                startActivity(intent);
            }
        });
        ivCollection = findViewById(R.id.collection);
        tvCollectionText = findViewById(R.id.tv_collection_text); // 假设你的TextView ID是这个
        // 为收藏按钮设置点击事件
        ivCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCollectionClick(v); // 调用切换收藏状态的方法
            }
        });
        tvCollectionText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCollectionClick(v); // 调用切换收藏状态的方法
            }
        });

        // 设置初始状态
        updateCollectionState(isCollected);


        // 初始化购物车管理类
        cancelImageButton = findViewById(R.id.cancel);
        // 设置关闭按钮的点击事件
        cancelImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 隐藏 xq_confirm 布局
                hideConfirmLayout();
            }
        });


        // 初始化 xq_confirm 布局
        xqConfirmLayout = findViewById(R.id.xq_confirm);
        xqConfirmLayout.setVisibility(GONE); // 默认设置为隐藏
        // 初始化按钮并设置点击事件

        Button buyNowButton = findViewById(R.id.buynow);
        buyNowButton.setOnClickListener(v -> showConfirmLayout());
        // 初始化控件
        quantityTextView = findViewById(R.id.quantity_text);
        totalPriceTextView = findViewById(R.id.total_price_text);
        plusButton = findViewById(R.id.plus_button);
        minusButton = findViewById(R.id.minus_button);
        // 设置初始总价
        updateTotalPrice();

        // 设置加号按钮点击事件
        plusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                quantity++;
                updateTotalPrice();
            }
        });
        // 设置减号按钮点击事件
        minusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (quantity > 1) {
                    quantity--;
                }
                updateTotalPrice();
            }
        });


        //店铺点击事件

        LinearLayout shopLinearLayout=findViewById(R.id.shop);
        shopLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用方法跳转到 ActivityShop
                redirectToActivityShop();
            }
        });
        //客服点击事件
        // 在DetailsActivity的onCreate方法中，找到客服按钮对应的LinearLayout
        LinearLayout messageLayout = findViewById(R.id.message);
// 为客服按钮设置点击事件
        messageLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 创建Intent启动MessageChartActivity
                Intent intent = new Intent(DetailsActivity.this, MessageChartActivity.class);
                // 可以传递需要的额外信息，例如客服的标识或名称
                intent.putExtra("user", "客服");
                // 启动MessageChartActivity
                startActivity(intent);
            }
        });

        // 获取电话图标的 ImageView 控件
        ImageView phoneImageView = findViewById(R.id.phone);
        // 设置点击事件
        phoneImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用方法显示对话框
                showCallDialog();
            }
        });
        //进店逛逛点击事件
        ImageButton shopButton=findViewById(R.id.shop_1);
        shopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                redirectToActivityShop();

            }
        });
        // 获取确定按钮并设置点击事件
        Button determineButton = findViewById(R.id.xq_determine);
        determineButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPaymentConfirmationDialog();
            }
        });

        // 获取启动此 Activity 的 Intent
        Intent intent = getIntent();
        // 从 Intent 中获取传递过来的 news_Id
        int goodsId = intent.getIntExtra("GOODS_ID_KEY", 0);
        Log.d("ProductDetailActivity", "GOODS_ID_KEY2: " + goodsId);
        isCollected = isGoodsCollected(goodsId);
        updateCollectionState(isCollected);
        // 查询news内容
        mProductDetailPresenter.getGoodsIdList(goodsId);

        // 检查商品是否被收藏

    }

    // 更新收藏状态的显示
    private void updateCollectionState(boolean isCollected) {
        if (isCollected) {
            ivCollection.setImageResource(R.drawable.shoucang_2); // 设置已收藏的图标
            tvCollectionText.setText("已收藏"); // 设置文本为“已收藏”
            tvCollectionText.setTextColor(ContextCompat.getColor(this, R.color.green)); // 设置文本颜色为绿色
        } else {
            ivCollection.setImageResource(R.drawable.shoucang); // 设置未收藏的图标
            tvCollectionText.setText("收藏"); // 设置文本为“收藏”
            tvCollectionText.setTextColor(ContextCompat.getColor(this, R.color.grey)); // 设置文本颜色为灰色
        }
    }

    // 收藏按钮的点击事件
    public void onCollectionClick(View view) {
        // 切换收藏状态
        isCollected = !isCollected;
        Log.d("TAG", "isCollected: " + isCollected);
        if (goods != null) {
            goods.setCollect(isCollected); // 更新Goods对象的收藏状态
        }

        // 更新数据库中的收藏状态
        if (goods != null) {
            updateDatabaseCollectState(goods.getId(), isCollected);
        }

        // 保存收藏状态到 SharedPreferences
        saveCollectedGoodsToSharedPreferences(goods.getId(), isCollected);

        // 更新 UI 显示收藏状态
        updateCollectionState(isCollected);
    }

    private void updateDatabaseCollectState(int goodsId, boolean isCollected) {
        ContentValues values = new ContentValues();
        values.put("is_collect", isCollected ? 1 : 0);

        // 更新数据库
        int rowsAffected = getContentResolver().update(
                Uri.parse("content://com.jlastu.znb.provider/goods"),
                values,
                "_id = ?",
                new String[]{String.valueOf(goodsId)}
        );

        if (rowsAffected > 0) {
            Toast.makeText(this, "收藏状态更新成功", Toast.LENGTH_SHORT).show();
            Log.d("TAG", "updateDatabaseCollectState: ");
        } else {
            Toast.makeText(this, "收藏状态更新失败", Toast.LENGTH_SHORT).show();
        }
    }

    // 该方法用于显示 xq_confirm 布局
    private void showConfirmLayout() {
        if (xqConfirmLayout.getVisibility() == GONE) {
            xqConfirmLayout.setVisibility(VISIBLE); // 显示布局
        }
    }

    // 如果需要隐藏布局，您可以创建一个类似的方法
    private void hideConfirmLayout() {
        if (xqConfirmLayout.getVisibility() == VISIBLE) {
            xqConfirmLayout.setVisibility(GONE); // 隐藏布局
        }
    }

    // 跳转到 ActivityShop 的方法
    private void redirectToActivityShop() {
        // 创建一个新的 Intent 来启动 ActivityShop
        Intent intent = new Intent(DetailsActivity.this, ShopActivity.class);
        // （可选）向 ActivityShop 传递数据
        // intent.putExtra("KEY", value);

        // 启动 ActivityShop
        startActivity(intent);
    }

    private void showCallDialog() {
        // 创建 AlertDialog.Builder 实例
        AlertDialog.Builder builder = new AlertDialog.Builder(DetailsActivity.this);
        // 设置对话框标题
        builder.setTitle("拨打电话");
        // 设置对话框消息
        builder.setMessage("是否拨打电话123669？");

        // 设置拨打电话的逻辑
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 调用拨打电话的方法
                callPhoneNumber("123669");
            }
        });

        // 设置取消按钮
        builder.setNegativeButton("否", null);

        // 显示对话框
        builder.create().show();
    }

    // 拨打电话的方法
    private void callPhoneNumber(String phoneNumber) {
        // 创建拨打电话的 Intent
        Intent intent = new Intent(Intent.ACTION_CALL);
        // 设置拨打的电话号码
        intent.setData(Uri.parse("tel:" + phoneNumber));

        // 检查是否有应用可以处理拨打电话的 Intent
        if (ActivityCompat.checkSelfPermission(DetailsActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // 如果没有拨打电话权限，则请求权限
            ActivityCompat.requestPermissions(DetailsActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
        } else {
            // 如果有权限，直接启动拨打电话的 Intent
            startActivity(intent);
        }
    }

    // 处理权限请求结果的方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 如果用户同意授权拨打电话权限，则拨打电话
            callPhoneNumber("123669");
        }
    }
    private void updateTotalPrice() {
        // 更新数量显示
        quantityTextView.setText(String.valueOf(quantity));
        // 计算并更新总价显示
        double totalPrice = quantity * pricePerUnit;
        totalPriceTextView.setText("总价：¥" + String.format("%.1f", totalPrice));
    }
    // 显示支付确认对话框的方法
    private void showPaymentConfirmationDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(DetailsActivity.this);
        builder.setTitle("确认支付");
        builder.setMessage("是否立即支付？");

        builder.setPositiveButton("立即支付", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户选择立即支付，处理支付逻辑
                handleImmediatePayment();
            }
        });

        builder.setNegativeButton("稍后支付", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户选择稍后支付，可以进行其他操作或不进行操作
                handleLaterPayment();
            }
        });

        builder.create().show();
    }

    // 处理立即支付的逻辑
    private void handleImmediatePayment() {
         // 这里假设你已经获取了必要的支付信息，例如订单ID和支付金额
        String orderId = "your_order_id"; // 订单ID，应该从你的订单系统中获取
        double paymentAmount = quantity * pricePerUnit; // 根据用户选择的数量计算支付金额

        // 显示加载提示，告知用户正在处理支付
        ProgressDialog progressDialog = new ProgressDialog(DetailsActivity.this);
        progressDialog.setMessage("正在支付...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        // 调用支付API的伪代码，实际中你需要替换为真实的支付API调用
        boolean isPaymentSuccess = performPaymentApiCall(orderId, paymentAmount);

        // 根据支付结果处理逻辑
        if (isPaymentSuccess) {
            // 支付成功
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 可能需要更新UI，例如标记订单为已支付
                    updateOrderStatus(orderId, "已支付");
                    // 隐藏加载提示
                    progressDialog.dismiss();
                    // 提示用户支付成功
                    Toast.makeText(DetailsActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    // 导航到待收货页面或其他页面
                    navigateToReceiptPage(orderId);
                }
            });
        } else {
            // 支付失败
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 隐藏加载提示
                    progressDialog.dismiss();
                    // 提示用户支付失败
                    Toast.makeText(DetailsActivity.this, "支付失败，请重试", Toast.LENGTH_SHORT).show();
                    // 可以导航到支付失败页面或保留在当前页面
                }
            });
        }
    }

    // 执行支付API调用的伪代码方法
    private boolean performPaymentApiCall(String orderId, double amount) {

        try {
            // 模拟网络请求
            Thread.sleep(2000); // 模拟网络延迟
            // 假设支付总是成功
            return true;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 更新订单状态的示例方法
    private void updateOrderStatus(String orderId, String status) {
        // 这里应该有更新订单状态的逻辑，例如调用后端API
        // 以下代码仅为示例
        System.out.println("订单 " + orderId + " 更新为 " + status);
    }

    // 导航到待收货页面的示例方法
    private void navigateToReceiptPage(String orderId) {
        // 这里应该有导航到待收货页面的逻辑
        // 以下代码仅为示例
        Intent intent = new Intent(DetailsActivity.this, OrdersActivity.class);
        intent.putExtra("ORDER_ID", orderId);
        startActivity(intent);
    }



    // 处理稍后支付的逻辑
    private void handleLaterPayment() {
        // 实现稍后支付的逻辑，例如记录用户的选择或导航到待支付页面
    }

    @Override
    public void onClick(View v) {
    }

    @Override
    public void showGoodsList(List<Goods> goodsList) {
        Goods firstGoods = goodsList.get(0);
        this.goods = firstGoods;
        Goods goods = goodsList.get(0);
        //商品内容
        tvProductName.setText(goods.getName());
        tvProductPrice.setText("¥ " + goods.getPrice() + "/" + goods.getUnit());
        tvProductAddress.setText(goods.getAddress());

        //商品图片
        List<Photo> photoList = goods.getPhotoList();
        if (photoList != null && !photoList.isEmpty()) {
            // 设置主图片
            byte[] byteArray = photoList.get(0).getData();
            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
            imgProduct.setImageBitmap(bitmap);
            // 设置详情图片
            for (int i = 1; i < photoList.size(); i++) {
                byteArray = photoList.get(i).getData();
                bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

                ImageView imageView = new ImageView(this);
                imageView.setImageBitmap(bitmap);
                imageView.setLayoutParams(new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, 500)); // 调整图片大小
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(0, 0, 0, 0);
                imgProductDetailContainer.setImageBitmap(bitmap);
                //imgProductDetailContainer.addView(imageView);
            }
        } else {
            //没有查到图片显示默认图片
            imgProduct.setImageResource(R.mipmap.ic_launcher);
        }
    }

    private void saveCollectedGoodsToSharedPreferences(int goodsId, boolean isCollected) {
        SharedPreferences preferences = getSharedPreferences("CollectedGoods", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        Set<String> collectedGoodsIdsStr = preferences.getStringSet("collected_goods_ids", new HashSet<String>());

        Set<Integer> collectedGoodsIds = new HashSet<>();
        for (String idStr : collectedGoodsIdsStr) {
            collectedGoodsIds.add(Integer.parseInt(idStr));
        }

        if (isCollected) {
            collectedGoodsIds.add(goodsId); // 添加到集合中
        } else {
            collectedGoodsIds.remove(goodsId); // 从集合中移除
        }

        // 将整数集合转换回字符串集合进行保存
        Set<String> collectedGoodsIdsStrNew = new HashSet<>();
        for (int id : collectedGoodsIds) {
            collectedGoodsIdsStrNew.add(String.valueOf(id));
        }

        editor.putStringSet("collected_goods_ids", collectedGoodsIdsStrNew);
        editor.apply();
    }

    public boolean isGoodsCollected(int goodsId) {
        SharedPreferences preferences = getSharedPreferences("CollectedGoods", MODE_PRIVATE);
        Set<String> collectedGoodsIdsStr = preferences.getStringSet("collected_goods_ids", new HashSet<String>());
        Set<Integer> collectedGoodsIds = new HashSet<>();
        for (String idStr : collectedGoodsIdsStr) {
            collectedGoodsIds.add(Integer.parseInt(idStr));
        }
        return collectedGoodsIds.contains(goodsId);
    }

}
